#pragma once
#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <string>
#include <cstring>
#include "Log.hpp"

class Sock
{
private:
    const static int gbacklog = 20;

public:
    Sock() {}
    // 1.创建套接字
    static int Socket()
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(ERROR, "create sock fail,%d:%s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "create sock success,%d", listensock);
        return listensock;
    }
    // 2.bind
    static void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = inet_addr(ip.c_str());
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(ERROR, "bind fail,%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "bind success");
    }

    // 3.设定监听状态
    static void Listen(int sock)
    {
        if (listen(sock, gbacklog) < 0)
        {
            logMessage(ERROR, "listen fail,%d:%s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "listen success");
    }
    // 4.获取连接
    //  一般经验
    //  const std::string &: 输入型参数
    //  std::string *: 输出型参数
    //  std::string &: 输入输出型参数
    static int Accept(int listensock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int service_sock = accept(listensock, (struct sockaddr *)&src, &len); // 返回提供服务的套接字
        // 没有链接的时候阻塞等待
        if (service_sock < 0) // 连接失败
        {
            logMessage(ERROR, "accept error, %d:%s", errno, strerror(errno));
            return -1;
        }
        logMessage(NORMAL, "accept success");
        if (port != nullptr)
            *port = ntohs(src.sin_port);
        if (ip != nullptr)
            *ip = inet_ntoa(src.sin_addr);
        return service_sock;
    }
    // 5.建立连接
    static bool Connect(int sock, const std::string &server_ip, const int16_t &server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());
        // 建立链接
        if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            logMessage(WARNING, "connect fail");
            return false;
        }
        return true;
    }
    ~Sock() {}
};